package de.lmu.mvs.lerngruppenfinder.interests;

import java.util.ArrayList;
import java.util.List;

/**
 * represents an interest in the interest three
 * 
 * @author Christopher Gebhardt
 * @date 24.06.2014
 *
 */
public class InterestNode {

	private InterestNode parent = null;
	
	private List<InterestNode> children = new ArrayList<InterestNode>();
	
	private int interestId = 0;
	
	private String interestName = "null";
	
	public boolean belongsToUser = false;
	
	public InterestNode(int id, String name){
		interestId = id;
		interestName = name;
	}
	
	/**
	 * Find a node by id
	 * @param id
	 * @return node or null if not found
	 */
	public InterestNode find(int id){
		if(interestId == id){
			return this;
		} else {
			InterestNode result = null;
			for (InterestNode node : children) {
				result = node.find(id);
				if(result != null){
					return result;
				}
			}
			return result;
		}
	}
	
	/**
	 * Find a node by its name
	 * @param name
	 * @return node or null if not found
	 */
	public InterestNode find(String name){
		if(interestName.equalsIgnoreCase(name)){
			return this;
		} else {
			for (InterestNode node : children) {
				InterestNode result = node.find(name);
				if(result != null){
					return result;
				}
			}
		}
		return null;
	}
	
	public InterestNode setParent(InterestNode parent){
		this.parent = parent;
		return this;
	}
	
	public InterestNode setChildren(List<InterestNode> children){
		this.children = children;
		return this;
	}
	
	public InterestNode addChildren(InterestNode... children){
		for (InterestNode node : children) {
			this.children.add(node);
		}
		return this;
	}

	public int getInterestId() {
		return interestId;
	}

	public InterestNode setInterestId(int interestId) {
		this.interestId = interestId;
		return this;
	}

	public String getInterestName() {
		return interestName;
	}

	public InterestNode setInterestName(String interestName) {
		this.interestName = interestName;
		return this;
	}

	public InterestNode getParent() {
		return parent;
	}

	public List<InterestNode> getChildren() {
		return children;
	}
	
	public boolean isLeaf(){
		return (children.size() < 1);
	}
	
	/**
	 * @return copy of this node without children or parent
	 */
	public InterestNode copyNodeOnly(){
		return new InterestNode(interestId, interestName);
	}
	
	/**
	 * @return copy of this node with children and without parent
	 */
	public InterestNode copy(){
		return new InterestNode(interestId, interestName)
			.setChildren(children);
	}
	
	public List<Integer> getAllInterests(){
		List<Integer> interets = new ArrayList<Integer>();
		interets.add(interestId);
		
		if(children.size() > 0){
			for (InterestNode child : getChildren()) {
				interets.addAll(child.getAllInterests());
			}
		}
		return interets;
	}
}
